package com.telnetnz.ticketdesk.action.attachment;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.rockbb.common.simpleframe.config.SimpleConfig;
import com.telnetnz.ticketdesk.action.base.BasicSessionPageAccAction;
import com.telnetnz.ticketdesk.bean.Attachment;
import com.telnetnz.ticketdesk.service.AttachmentService;

public class AttachmentAction extends BasicSessionPageAccAction
{
	private static Logger logger = Logger.getLogger(AttachmentAction.class);

	public String doDownload()
	{
		RequestBean bean = new DefaultRequestBean();
		long id = bean.getLong("id", 0L);
		Attachment attachment = AttachmentService.getAttachment(id);
		if (attachment == null)
			return this.message_box(
					langRes.get("global.error"),
					langRes.get("attachment.attachment-not-exist-redirect", new String[]{bean.getRedirect()}),
					bean.getRedirect(),
					2);
		else if (!isSuperSession() && !attachment.isViewable(getSession().getSession_uuid()))
			return this.message_box(
					langRes.get("global.no-permission"),
					langRes.get("global.no-permission-redirect", new String[]{bean.getRedirect()}),
					bean.getRedirect(),
					2);
		File file = new File(SimpleConfig.getConfig("file_physical_path") + SimpleConfig.getConfig("file_for_static") + attachment.getPath());
		if (file.exists() && file.isFile())
		{
			try {
				byte[] bytes = FileUtils.readFileToByteArray(file);
				this.set_streambytes(
						attachment.getMimeType(),
						"attachment", 
						attachment.getName(), 
						bytes);
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return SUCCESS;
	}
}
